package com.avic.rong.course.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.course.adapter.PeiXunBookShelfRvAdapter;
import com.avic.rong.course.bean.BookBackBean;
import com.avic.rong.course.showapi.BookBackApi;
import com.avic.rong.course.showapi.JoinStudyPlainApi;
import com.avic.rong.course.showapi.RemoveBackApi;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 我的书架
 */
public class PeiXunBookShelfActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {


    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ll_root)
    LinearLayout llRoot;
    @BindView(R.id.peixun_bookshelf_rv)
    RecyclerView peixunBookshelfRv;
    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private PeiXunBookShelfRvAdapter bookShelfRvAdapter;
    private BookBackApi bookBackApi;
    private int mPosition;

    private ArrayList<BookBackBean.ResultListBean> dataList = new ArrayList<>();
    @Override
    protected int getContentViewId() {
        return R.layout.activity_pei_xun_book_shelf;
    }

    @Override
    protected void initView() {

        ButterKnife.bind(this);
        tvTitle.setText("我的书架");
        ivRight.setImageResource(R.mipmap.gouwuche_dot);


        peixunBookshelfRv.setLayoutManager(new LinearLayoutManager(this));
        bookShelfRvAdapter = new PeiXunBookShelfRvAdapter(this,dataList);
        peixunBookshelfRv.setAdapter(bookShelfRvAdapter);


        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        if (SharedPreferencesUtil.isLogin()) {
            initData();
        } else {
            Intent intent = new Intent(PeiXunBookShelfActivity.this, LoginPhoneActivity.class);
            intent.putExtra("come_from", "PeiXunBookShelfActivity");
            startActivity(intent);
            finish();
        }
        bookShelfRvAdapter.setDeleteBook(new PeiXunBookShelfRvAdapter.DeleteBook() {
            @Override
            public void onDelete(BookBackBean.ResultListBean.DataBean bean, int position) {
                mPosition = position;
                RemoveBackApi removeBackApi = new RemoveBackApi(PeiXunBookShelfActivity.this, removeBackListener);
                removeBackApi.setArgument(SharedPreferencesUtil.getLoginToken(), bean.getId());
                HttpManager.getInstance().doHttpDeal(removeBackApi);
            }
        });

    }

    //取消收藏成功
    HttpOnNextListener<BaseResultEntity> removeBackListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                dataList.remove(mPosition);
                bookShelfRvAdapter.notifyDataSetChanged();
                if (dataList.size() <= 0) {
                    loading_layout.setStatus(LoadingLayout.EMPTY);
                    loading_layout.setEmptyText("您还未添加过收藏哦~");
                    loading_layout.setEmptyImageVisible(true);
                    loading_layout.setEmptyImage(R.mipmap.collection_mpty);
                }
                ToastTools.showToast("取消收藏成功！");
            } else {
                ToastTools.showToast(context, baseResultEntity.getMsg());
            }
        }
    };

    private void initData() {
        Logger.i("-------------------token:" + SharedPreferencesUtil.getLoginToken());
        loading_layout.setStatus(LoadingLayout.LOADING);
        bookBackApi = new BookBackApi(this, bookBackListener);
        bookBackApi.setArgument(SharedPreferencesUtil.getLoginToken(), currentPageNumber, pageSize);
        HttpManager.getInstance().doHttpDeal(bookBackApi);
    }

    HttpOnNextListener<BaseResultEntity> bookBackListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            loading_layout.setStatus(LoadingLayout.SUCCESS);

            if (!ConstantsUtils.STATUS_SUCCESS_0000.equals(baseResultEntity.getCode())) {
                ToastTools.showToast(context, baseResultEntity.getMsg());
                return;
            }

            if (isRefresh) {
                dataList.clear();
            }

            BookBackBean result = (BookBackBean) baseResultEntity.getResult();
            dataList.addAll(result.getResultList());
            bookShelfRvAdapter.notifyDataSetChanged();


            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (dataList == null || dataList.size() <= 0) {
                        loading_layout.setStatus(LoadingLayout.EMPTY);
                        loading_layout.setEmptyText("您还未添加过收藏哦~");
                        loading_layout.setEmptyImageVisible(true);
                        loading_layout.setEmptyImage(R.mipmap.collection_mpty);
                    }
                }
            });

            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }

        }

        @Override
        public void onError(final Throwable e) {
            if (isRefresh) {
                refreshLayout.finishRefresh();
            } else {
                refreshLayout.finishLoadMore();
            }
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }


    };


    @Override
    public void onLoadMore(RefreshLayout refreshLayout) {
        isRefresh = false;
        currentPageNumber = currentPageNumber + 1;
        bookBackApi.setPageNo(currentPageNumber);
        HttpManager.getInstance().doHttpDeal(bookBackApi);

    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {

        isRefresh = true;
        currentPageNumber = 1;
        bookBackApi.setPageNo(currentPageNumber);
        HttpManager.getInstance().doHttpDeal(bookBackApi);

    }


    @OnClick(R.id.iv_back)
    public void goBack(View view) {
        onBackPressed();
    }

    @OnClick(R.id.iv_right)
    public void goDirect(View view) {
        showPopup(PeiXunBookShelfActivity.this, llRoot);
    }

    @Override
    protected void addListener() {

    }


    //加入书架
    public void joinStudyPlain(String courseId) {
        JoinStudyPlainApi classMuLuApi = new JoinStudyPlainApi(this, simpleOnNextListener, courseId, SharedPreferencesUtil.getLoginToken());
        classMuLuApi.setCache(false);
        HttpManager.getInstance().doHttpDeal(classMuLuApi);
    }

    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(PeiXunBookShelfActivity.this, subjects.getMsg());
                Logger.e("cjx", subjects.getMsg());
                return;
            }
            ToastTools.showToast(PeiXunBookShelfActivity.this, "加入书架成功！");
        }

        @Override
        public void onError(final Throwable e) {
            Logger.e("cjx", "培训课时目录列表数据：" + e.getMessage());
        }
    };


    public static Intent queryIntent(Context context) {
        Intent intent = new Intent(context, PeiXunBookShelfActivity.class);
        return intent;
    }

}
